#pragma once
#include<iostream>
#include<cstdio> //perror
#include<cstdlib> //exit
#include<string>
#include<sys/types.h> //mkfifo
#include<sys/stat.h> //mkfifo
#include<unistd.h>
#include<fcntl.h>


#define DEFAULT_PATH "."
#define FILE_NAME "common"


#define ERR_EXIT(m)    \
do                     \
{                      \
    perror(m);         \
    exit(EXIT_FAILURE);\
}while(0)


class NamedPipe
{
public:
    NamedPipe(const std::string& name = FILE_NAME)
    :_name(name)
    {
        umask(0);
        int ret = mkfifo(_name.c_str(),0666);
        if(ret < 0)
        {
            ERR_EXIT("mkfifo");
        }
        std::cout << "管道文件创建成功!!!\n";
    }

    ~NamedPipe()
    {
        unlink(FILE_NAME);
    }
private:
    std::string _name;
    std::string _path;
};


class FileOpener
{
public:
    void OpenForRead()
    {
        int fd = open(_path.c_str(),O_CREAT | O_TRUNC | O_RDONLY);
        if(fd < 0)
        {
            ERR_EXIT("open");
        }
        std::cout << "open函数执行完毕,文件:" << _path <<"已经打开\n";
        _fd = fd;
    }
    void OpenForWrite()
    {
        int fd = open(_path.c_str(),O_APPEND|O_WRONLY);
        if(fd < 0)
        {
            ERR_EXIT("open");
        }
        _fd = fd;
    }
    void Write()
    {
        std::string tmp;
        std::cout << "输入想要发送的信息" << std::endl;
        std::getline(std::cin , tmp , '\n');
        write(_fd,tmp.c_str(),tmp.size());
    }
    int Read()
    {
        std::cout << "服务端等待输入\n";
        char buffer[256];
        int num = read(_fd,buffer,sizeof(buffer));
        if(num > 0)
        {
            buffer[num] = '\0';
            std::cout << "收到消息: " <<buffer << std::endl;
            return num;
        }
        else if(num == 0)
        {
            std::cout << "结束通信,拜拜\n";
            return 0;
        }
        else
        {
            ERR_EXIT("read");
        }
    }
private:
    std::string _name = FILE_NAME;
    std::string _path = FILE_NAME;
    int _fd = -1;
};



